﻿// SPDX-FileCopyrightText: 2021 - 2022 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#pragma once

#include "netclientjob.h"
#include "src/netlistener/netlistenerjob.h"

#include <QObject>
#include <QThread>
#include <QDBusInterface>

enum AgentLoginState {
    NONE = 0, // 无登录操作

    BARCODE_WAITTING, // 等待扫码
    BARCODE_SCANNED, // 二维码已扫码但未确认登录
    BARCODE_VERIFING, // 二维码验证中
    BARCODE_FAILED, // 二维码验证失败
    BARCODE_SUCCESS, // 二维码验证成功
    BARCODE_EXPIRED, // 二维码超时

    FACE_WAITTING, // 等待服务器人脸数据
    FACE_FAILED, // 人脸验证失败
    FACE_SUCCESS, // 人脸验证成功

    HTTP_RESPONSE_OUT_OF_TIME,
    LOCK_MISMATCH_USER // 锁屏时，用户不一致
};

enum AgentLoginType {
    IDLE,
    BARCORD_2D,
    FACE
};

class NetClientModel : public QObject
{
    Q_OBJECT
public:
    explicit NetClientModel(QObject *parent = nullptr);
    ~NetClientModel();

Q_SIGNALS:
    void requestThreadToRegisterClient(const QString &clientCode);
    void requestThreadToGetQrCode();
    void requestThreadToCheckQrCode();
    void requestThreadToQueryLocalUserInfo();
    void requestThreadToSaveLocalUserInfo(const QString &localUserName,
                                          const QString &localUserFullName,
                                          const QString &localUserPasswd);
    void requestThreadToTryCreateLocalUser();
    void requestThreadToCheckFace(const QString &imgData);
    void requestThreadToCheckHttpSrvValidity();
    void requestThreadToStopHttpReply();

private Q_SLOTS:
    void onRequestRegisterClient(const QString &clientCode);
    void onRequestGetQrCode();
    void onRequestCheckQrCode();
    void onRequestLoginLocalUserInfo();
    void onRequestCheckFace();
    void onRequestSetFaceStateToAgent();
    void onNotifyLoginTypeChanged(int type);
    void onRequestCheckHttpSrvValidity();

    void onGetQrCodeFinished(bool successed, const QString &qr);
    void onCheckQrCodeFinished(bool successed, NetClientJob::QrStatus status);
    void onQueryLocalUserInfoFinished(bool successed, const QString &localUserName);
    void onSaveLocalUserInfoFinished(bool successed, const QString &localUserName);
    void onRegisterClientFinished(bool successed, const QString &clientCode);
    void onCheckFaceFinished(bool successed);

    void onCheckHttpSrvValidityFinished(bool valid);

private:
    void setAgentLoginState(AgentLoginState state);
    void setHttpSrvValidityToAgent(bool valid);

private:
    QThread *m_jobThread;
    NetClientJob *m_job;
    NetListenerJob *m_listenerJob;
    bool m_needSetHttpSrvValidityToAgent; // 初始化时需要将服务器可行性设置到agent
    bool m_isHttpSrvValid;
    QDBusInterface *m_agentDbusIfc;
    AgentLoginType m_agentLoginType;
    AgentLoginState m_agentLoginState;

    bool m_isInLoginLocalUserInfo;
};
